package com.bjpowernode.boss.common.cilent.mail;

import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MailClient {
    @Resource
    private JavaMailSender  mailSender;
    //简单邮件
    public boolean sendSimpleMail(MailProp mailProp){
        try {
            SimpleMailMessage simple = new SimpleMailMessage();
            simple.setFrom(mailProp.getFrom());
            simple.setTo(mailProp.getTo());
            simple.setSubject(mailProp.getSubject());
            simple.setText(mailProp.getText());
            mailSender.send(simple);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    //发送复杂邮件
    public boolean sendAttachMail(MailProp mailProp) {
        try {
            MimeMessage mime = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mime,true);
            helper.setFrom(mailProp.getFrom()); //发送者
            helper.setTo(mailProp.getTo());       //接收者
            helper.setSubject(mailProp.getSubject());  //主题
            helper.setText(mailProp.getText());        //正文
            //附件
            List<AttachFile> attachFiles = mailProp.getAttachFiles();
            if(attachFiles!=null){
                for (AttachFile attachFile : attachFiles) {
                    helper.addAttachment(attachFile.getName(),attachFile.getFile());
                }
            }
            mailSender.send(helper.getMimeMessage());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
